package lobster.net.verificationcode;

import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    public SMSBroadcastReceiver receiver;

    private String path;

    private String code;

    private String result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        receiver = new SMSBroadcastReceiver();
        IntentFilter filter = new IntentFilter();

        String ip = readUrl();
        final EditText editText = (EditText) findViewById(R.id.editText);

        if (!ip.equals("") && ip != null) {
            editText.setText(ip);
        }


        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(receiver, filter);
        //实例化过滤器并设置要过滤的广播
        receiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
            @Override
            public void OnReceived(String message) {

                Pattern pattern = Pattern.compile("(\\d{6})");
                Matcher matcher = pattern.matcher(message);
                if (matcher.find()) {
                    code = matcher.group(1);
                }
                System.out.println("获取到验证码：");
                System.out.println(code);

                final String ipAddress = editText.getText().toString();

                writeUrl(ipAddress);

                doget();
                path = "http://" + ipAddress;

                Toast.makeText(MainActivity.this, message + "ipAddress=" + ipAddress, Toast.LENGTH_LONG).show();

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(receiver);
    }


    private void doget() {
        new Thread(getThread).start();
    }


    private Thread getThread = new Thread() {
        public void run() {
            HttpURLConnection connection = null;
            try {
                path = path + "/verificationCode.do?code=" + code;
//                URL url = new URL("http://172.16.6.15:8080/verificationCode.do?code=556889");
                URL url = new URL(path);
                connection = (HttpURLConnection) url.openConnection();
                // 设置请求方法，默认是GET
                connection.setRequestMethod("GET");
                // 设置字符集
                connection.setRequestProperty("Charset", "UTF-8");
                // 设置文件类型
                connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");


                if (connection.getResponseCode() == 200) {
                    InputStream is = connection.getInputStream();
//                    result = StringStreamUtil.inputStreamToString(is);

                    Message msg = Message.obtain();
                    msg.what = 0;
//                    getHandler.sendMessage(msg);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }

        ;
    };


    String readUrl() {
        String url = null;
        SharedPreferences sharedPreferences = getSharedPreferences("verifycode", 0);
        url = sharedPreferences.getString("URL", "");
        return url;
    }

    void writeUrl(String url) {
        SharedPreferences sharedPreferences = getSharedPreferences("verifycode", 0);
        sharedPreferences.edit().putString("URL", url).commit();

    }


    /**
     * 单击事件，保存页面上的输入框
     * @param v
     */
    public void click(View v) {
        EditText editText = (EditText) findViewById(R.id.editText);

        String ipAddress = editText.getText().toString();

        writeUrl(ipAddress);
    }

}
